package com.smart.manager.weixin.mp.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import com.alicp.jetcache.Cache;
import com.smart.common.cache.CacheService;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;
import com.smart.common.entities.option.SelectOption;
import com.smart.manager.weixin.mp.cfg.WxmpCmdRunner;
import com.smart.manager.weixin.mp.entities.bodys.RWeixnMpAccount;
import com.smart.manager.weixin.mp.entities.enums.WeixinMpAccountType;
import com.smart.manager.weixin.mp.entities.models.WeixinMpAccount;
import com.smart.manager.weixin.mp.entities.models.query.QWeixinMpAccount;
import io.ebean.DB;
import io.ebeaninternal.server.util.Str;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 公众号接入配置 数据仓库
 *
 * @author Administrator
 * @date 2023/04/02
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class WxmpAccountRepository {


    private final CacheService cacheService ;
    private final WxmpCmdRunner wxmpCmdRunner;

    public Page<WeixinMpAccount> pageList(RWeixnMpAccount.SearchBody search) {


        QWeixinMpAccount query = new QWeixinMpAccount();
        Opt.ofBlankAble(search.getName()).ifPresent(x -> query.name.contains(x));
        query.order().id.desc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<WeixinMpAccount>().load(query.findPagedList());
    }

    public void add(RWeixnMpAccount.EditBody body) {
        Assert.equals(WeixinMpAccountType.SERVICE_ACCOUNT_AUDITED, body.getType(), "当前系统仅支付已认证过的订阅号接入");

        WeixinMpAccount weixinMpAccount = new QWeixinMpAccount().appId.eq(body.getAppId()).setMaxRows(1).findOne();
        Assert.isNull(weixinMpAccount, "公众号信息已存在");
        WeixinMpAccount rs = BeanUtil.copyProperties(body, WeixinMpAccount.class);
        rs.setAuthTime(LocalDateTime.now()).save();

        wxmpCmdRunner.addConfig(rs);

    }


    public void update(Long id, RWeixnMpAccount.EditBody body) {

        QWeixinMpAccount query = new QWeixinMpAccount();
        WeixinMpAccount record = query.id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
        BeanUtil.copyProperties(body, record);
        Objects.requireNonNull(record).update();
        wxmpCmdRunner.removeConfig(body.getAppId());
        wxmpCmdRunner.addConfig(record);
    }

    public int delByIds(List<Long> ids) {
        List<WeixinMpAccount> list = new QWeixinMpAccount().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);
        for (WeixinMpAccount account : list) {
            wxmpCmdRunner.removeConfig(account.getAppId());
        }
        return DB.deleteAll(list);


    }


    /**
     * @return {@code List<SelectOption>}
     */
    public List<SelectOption> getOptions() {
        QWeixinMpAccount query = new QWeixinMpAccount();
        return query.findStream()
                .map(x -> new SelectOption().setLabel(x.getName())
                        .setValue(x.getAppId()).setDisabled(false))
                .collect(Collectors.toList());
    }


    /** 获取默认公众号APPID
     * @return {@link String}
     */
    public String getDefaultAppId() {
     String cacheKey="wxmp_default_appid" ;
     Cache<String, String> kvCache = cacheService.getKvCache();
     String s = kvCache.get(cacheKey);
     if (StrUtil.isNotBlank(s)) {
         return  s ;
     }


     QWeixinMpAccount query = new QWeixinMpAccount();
     String result = query.select(QWeixinMpAccount.Alias.appId).setMaxRows(1).findSingleAttribute();
     Assert.notBlank(result, "当前系统没有配置任何公众信息") ;
     kvCache.put(cacheKey ,result);
     return result;




 }
}
